package com.itheima.d3_collections;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

//目标：掌握Collections工具类常见方法的使用
public class Demo2 {
    public static void main(String[] args) {
        //static <T> boolean addAll(Collection<? super T> c, T...elements)：给集合批量添加元素
        //需求：往一个ArrayList集合中，一次性批量添加数据"吴某凡", "罗某祥", "李某峰", "李某迪"
        ArrayList<String> list = new ArrayList<>();
        Collections.addAll(list, "吴某凡", "罗某祥", "李某峰", "李某迪");
        System.out.println("批量添加数据后：" + list);

        //static void shuffle(List<?> list)：打乱List集合中的元素顺序
        //需求：将list集合中数据顺序打乱
        Collections.shuffle(list);
        System.out.println("打乱顺序后：" + list);
        System.out.println("--------------------");

        //static <T> void sort(List<T> list)：对List集合中的元素进行升序排序
        //整数集合排序
        ArrayList<Integer> numList = new ArrayList<>();
        Collections.addAll(numList, 5, 1, 4, 2, 3);
        System.out.println("整数集合排序前：" + numList);
        Collections.sort(numList);
        System.out.println("整数集合排序后：" + numList);

        //字符串集合排序
        ArrayList<String> strList = new ArrayList<>();
        Collections.addAll(strList, "a", "d", "c", "b");
        System.out.println("字符串集合排序前：" + strList);
        Collections.sort(strList);
        System.out.println("字符串集合排序后：" + strList);
        System.out.println("--------------------");

        //自定义类型的List集合排序
        ArrayList<Student> stuList = new ArrayList<>();
        Student stu1 = new Student("张三", 23);
        Student stu2 = new Student("李四", 20);
        Student stu3 = new Student("王五", 25);
        Student stu4 = new Student("赵六", 22);
        Collections.addAll(stuList, stu1, stu2, stu3, stu4);

        //排序：代码报错，因为此时Student没有排序规则，没有实现Comparable接口！
        //解决：如果非要用这个方法，就要让Student实现Comparable接口，否则用另一个sort方法
        Collections.sort(stuList);
        System.out.println("自定义类型的集合排序后：" + stuList);

        //static <T> void sort(List<T> list, Comparator<? super T> c)：对List集合中元素，按照比较器对象指定的规则进行排序
        Collections.sort(stuList, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                //制定排序规则：年龄降序
                return o2.getAge() - o1.getAge();
            }
        });

        System.out.println("比较器制定排序规则，排序后：" + stuList);
    }


}
